/*
 * Created on 2005-11-4
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package com.tmpt.controller.filter;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.tmpt.dto.A2UserDto;
import com.tmpt.dto.ConstantDto;
import com.tmpt.utils.DateTool;
import com.tmpt.utils.WebUtils;


public class AddressFilter implements Filter {
	
	private static AddressFilter addressFilter = new AddressFilter();
	
	public AddressFilter() {
		super();
	}

	public void init(FilterConfig filterConfig) throws ServletException {}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		//request.setCharacterEncoding("gbk");
		if(!hasBadSql(request)){
			try{
				addressFilter.filerMethod(request);
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				filterChain.doFilter(request, response);
			}
		}
	}

	/**
	 * filter sql 注入攻击 
	 */
	private boolean hasBadSql(ServletRequest request1){
		HttpServletRequest request = (HttpServletRequest)request1;
		Enumeration<String> names = request.getParameterNames();
		StringBuffer sb = new StringBuffer();
		while(names.hasMoreElements()){
			String name = names.nextElement();
			String value = request.getParameter(name);
			if(value.indexOf("@")>0 && value.length()<35 && name.indexOf("email")!=-1){//email
				continue;
			}
			if(name.equals("__VIEWSTATE") 
					|| name.equals("method") 
					|| name.equals("vf")
					|| name.equals("signMsg")
					|| name.equals("merchantText")
					|| name.equals("description")
					|| name.equals("productNameShow")
					|| name.equals("productNameShowSearch")
					
					
					){
				continue;
			}
				
			if(hasSqlInj(value)){
				sb.setLength(0);
				sb.append("==>warning SQL injectiong:name:"+name+",value:"+value);
				sb.append("   ");
				sb.append("url:"+request.getRequestURI().toString());
				sb.append("   ");
				sb.append("ip:"+WebUtils.getRealIp(request));
				//System.out.println(sb.toString());
				return true;
			}
		}
		return false;
	} 
	private boolean hasSqlInj(String str)
	{
		String inj_str = " and &exec&insert &select &delete &update & count & * &% &chr &mid & master &truncate&char &declare & or &drop &<script&;&--&+&'";
		String inj_stra[] = inj_str.split("&");
		for (int i=0 ; i < inj_stra.length ; i++ )
		{
			if (str.indexOf(inj_stra[i])>=0 && str.length()>=15)
			{
				return true;
			}
		}
		return false;
	}
	public static void main(String[] args){
		AddressFilter add = new AddressFilter();
		//System.out.println(add.hasSqlInj("exec('select * from')"));
	}
	/**
	 * filer 调用处理方法
	 */
	public void filerMethod(ServletRequest arg0)throws Exception{
		HttpServletRequest request = (HttpServletRequest)arg0;
		//生成txt文件
		String filename = DateTool.getCurrentDateStr1("yyyy-MM-dd")+".txt";
		String path = request.getSession().getServletContext().getRealPath("/")+ File.separator + "AccessLog" + File.separator;
		String strFile = path+filename;
		File file = new File(strFile);
		boolean flag = false;
		synchronized(addressFilter){
			if(!file.exists()){
				flag = true;
				file.getParentFile().mkdir();
				if(!file.createNewFile())throw new IOException("create file:"+strFile+" failure");
			}
			java.io.BufferedWriter bw = new java.io.BufferedWriter(new java.io.OutputStreamWriter(
										new java.io.FileOutputStream(strFile,true)));
			if(flag==true){
				bw.write("IP, ");
				bw.write("URL, ");
				bw.write("WebLoginName, ");
				bw.write("MagSysLoginName, ");
				bw.write("Datetime, ");
				bw.newLine();
			}
			//get user information from session
			A2UserDto userDto = (A2UserDto)request.getSession().getAttribute(ConstantDto.MagSystemDtoSession);
			String WebLoginName="";
			String MagSysLoginName="";
			if(userDto!=null){
				MagSysLoginName = userDto.getLoginName();
			}
			
			bw.write(WebUtils.getRealIp(request)+", ");
			bw.write(request.getRequestURI().toString()+", ");
			bw.write(WebLoginName+", ");
			bw.write(MagSysLoginName+", ");
			bw.write(DateTool.getCurrentDateStr1("yyyy-MM-dd HH:mm:ss"));
			bw.newLine();
			bw.close();
		}
	}

	

	
	public void destroy() {}
	
	
}
